'use strict';

var app = angular.module('app', ['ui.load', 'ui.router', 'ui.tree', 'ngStorage', 'brantwills.paging', 'oc.lazyLoad', 'ngImgCrop']);
var v=new Date().getTime()
/* Controllers */
angular.module('app')
  .controller('AppCtrl', ['$scope', '$localStorage', '$window','$http','$state','$rootScope',
    function($scope,   $localStorage,   $window ,$http,$state,$rootScope) {

        // add 'ie' classes to html
        var isIE = !!navigator.userAgent.match(/MSIE/i);
        isIE && angular.element($window.document.body).addClass('ie');
        isSmartDevice($window) && angular.element($window.document.body).addClass('smart');
		
        // config
        $rootScope.app= $scope.app = {
            name: 'iFengChao',
            project_name:'../iFengChao-SYS-Web',
            version: '0.0.2',
            // for chart colors
            color: {
                primary: '#7266ba',
                info: '#23b7e5',
                success: '#27c24c',
                warning: '#fad733',
                danger: '#f05050',
                light: '#e8eff0',
                dark: '#3a3f51',
                black: '#1c2b36'
            },
            settings: {
                themeID: 1,
                navbarHeaderColor: 'bg-black-only',
                navbarCollapseColor: 'bg-dark-blue-only',
                asideColor: 'bg-black',

                headerFixed: true,
                asideFixed: true,
                asideFolded: false,
                asideDock: false,
                container: true
            }
        }

        $scope.defaultAvatar = $rootScope.defaultAvatar = 'res/img/np.png';
        $scope.isEmpty=$rootScope.isEmpty=function (v) {
            var type=Object.prototype.toString.call(v);
            if(type=='[object Object]'){
                if(Object.keys(v).length==0){
                    return false
                }else{
                    return true
                }
            }
            if(type=='[object String]'||type=='[object Array]'){
                if(v.length==0){
                    return false
                }else{
                    return true
                }
            }
            if(type=='[object Null]'||type=='[object Undefined]'){
                return false
            }
            if(type=='[object Number]'){
                return true
            }
        }
        $scope.logout = function(){
            return $http({
                method:'POST',
                url: $scope.app.project_name+'/logout'
            }).then(function(result){
                var d = result.data;
                if(d.httpCode==200){//注销成功
                    deleteUserInfo();
                    $state.go('access.login');
                }
            });
            function deleteUserInfo(){
                $.cookie('_ihome_uid',null);
            }
        }

        $scope.hyzpostdetail= function (postId)
        {
            /*  usercreateDialog() ;*/
            hyzactivate(postId);
            $(document).ready(function(){
                $('#myModal').modal({backdrop: 'false', keyboard: true});
                $("#myModal").modal('show');
            });
        }
        // 加载帖子的详情信息
        function hyzactivate(postId) {
            $scope.loading = true;
            $.ajax({
                url : $scope.app.project_name + '/postTask/read/postDetail',
                data: {'postId': postId}
            }).then(function(result) {
                $scope.loading = false;
                if (result.httpCode == 200) {
                    $scope.hyzPostrecord = result.data;

       } else {
                    $scope.msg = result.msg;
                }
                $scope.$apply();
            });
        }
        var img_index = 0;
        var img_src = "";
//如何调用？
        $scope.imglook=function(event) {
            $(".photo-mask").show();
            $(".photo-panel").show();
            img_src = $(event.target).attr("src");
            img_index = $(event.target).index();
            photoView($(event.target));
            $scope.img();
        }

        //自适应预览
        function photoView(obj) {
            if($(obj).width() >= $(obj).height()) {
                $(".photo-panel .photo-div .photo-img .photo-view-h").attr("class", "photo-view-w");
                $(".photo-panel .photo-div .photo-img .photo-view-w img").attr("src", img_src);
            } else {
                $(".photo-panel .photo-div .photo-img .photo-view-w").attr("class", "photo-view-h");
                $(".photo-panel .photo-div .photo-img .photo-view-h img").attr("src", img_src);
            }
            //此处写调试日志
            console.log(img_index);
        }$rootScope.alertModal =  $scope.alertModal = function (option) {
            $("#content").text(option.content)
            $("#messageModal").modal('show',true);
            $(".fade").hide();
            setTimeout(function () {
                $("#messageModal").modal('hide');
            },2000)
        }
        $rootScope.authorityalertModal =  $scope.authorityalertModal = function (option) {
            $("#authoritycontent").text(option.content)
            $("#authorityModal").modal('show',true);
            $(".fade").hide();
            setTimeout(function () {
                $("#authorityModal").modal('hide');
            },2000)
        }


        $scope.img=function() {

            //关闭
            $(".photo-close").click(function() {
                $(".photo-mask").hide();
                $(".photo-panel").hide();
            });
            //下一张
            $(".photo-panel .photo-div .arrow-next").click(function() {
                img_index++;
                if(img_index >= $(".demo li img").length) {
                    img_index = 0;
                }
                img_src = $(".demo li img").eq(img_index).attr("src");
                photoView($(".demo li img"));
            });
            //上一张
            $(".photo-panel .photo-div .arrow-prv").click(function() {
                img_index--;
                if(img_index < 0) {
                    img_index = $(".demo li img").length - 1;
                }
                img_src = $(".demo li img").eq(img_index).attr("src");
                photoView($(".demo li img"));
            });

        }
        $scope.alertModal_slow = function (option) {
            $("#content").text(option.content)
            $("#messageModal").modal('show',true);
            $(".fade").hide();
            setTimeout(function () {
                $("#messageModal").modal('hide');
            },5000)
        }

        $scope.Validate = function (form) {
            var flag = true;
            form.find(".require").each(function () {
                console.log($(this).val());
                if($(this).val()==""||$(this).val()==null){
                    $(this).tooltip({"trigger":'manual','title':$(this).data('title')+"不能为空"});
                    $(this).tooltip('show');
                    $(this).hover(function () {
                        $(this).tooltip('hide');
                    });
                    flag = false;
                    return false;
                }
            })
            form.find(".number").each(function () {
                var reg = new RegExp("^[0-9]+(.[0-9]{1,3})?$");
                if(!reg.test($(this).val())||$(this).val()==0){
                    $(this).tooltip({"trigger":'manual','title':$(this).data('title')+"输入为有效的数字"});
                    $(this).tooltip('show');
                    $(this).hover(function () {
                        $(this).tooltip('destroy');
                    });
                    flag = false;
                    return false;
                }
                var max = $(this).data('max');
                if(max!=""&&max!=null&&Number(max)<Number($(this).val())){
                    $(this).tooltip({"trigger":'manual','title':$(this).data('title')+$(this).data('maxtitle')});
                    $(this).tooltip('show');
                    $(this).hover(function () {
                        $(this).tooltip('destroy');
                    });
                    flag = false;
                    return false;
                }
                var min = $(this).data('min');
                if(min!=""&&min!=null&&Number(min)>=Number($(this).val())){
                    $(this).tooltip({"trigger":'manual','title':"必须大于"+$(this).data('title')});
                    $(this).tooltip('show');
                    $(this).hover(function () {
                        $(this).tooltip('destroy');
                    });
                    flag = false;
                    return false;
                }
            })
            return flag;
        }

        $localStorage.settings = $scope.app.settings;

        // save settings to local storage  暂不支持自定义布局
        /*if (angular.isDefined($localStorage.settings)) {
            $scope.app.settings = $localStorage.settings;
        } else {
            $localStorage.settings = $scope.app.settings;
        }*/
        $scope.$watch('app.settings', function () {
            if ($scope.app.settings.asideDock && $scope.app.settings.asideFixed) {
                // aside dock and fixed must set the header fixed.
                $scope.app.settings.headerFixed = true;
            }
            // save to local storage
            $localStorage.settings = $scope.app.settings;
        }, true);

        // angular translate
        //$scope.lang = { isopen: false };
        //$scope.langs = {en:'English', de_DE:'German', it_IT:'Italian'};
        function isSmartDevice($window) {
            // Adapted from http://www.detectmobilebrowsers.com
            var ua = $window['navigator']['userAgent'] || $window['navigator']['vendor'] || $window['opera'];
            // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
            return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
        }

		$.ajaxSetup({
			type : "POST",
			beforeSend: function(evt, request, settings) {
				//request.url = 'iFengChao-Web' + request.url;
			},
			error : function(jqXHR, textStatus, errorThrown) {
				switch (jqXHR.status) {
				case (404):
					alert("未找到请求的资源");
					break;
				}
			}
		});
		$(document).ajaxSuccess(function(event, xhr, settings) {
			if(xhr.responseJSON.httpCode == 401) {
				$state.go('access.login');
                return null;
            } else if(xhr.responseJSON.httpCode == 303) {
            }else if(xhr.responseJSON.httpCode == 403) {
                $scope.authorityalertModal({"content":xhr.responseJSON.msg});
            }else if(xhr.responseJSON.httpCode != 200) {

            } else {
				if(xhr.responseJSON.data && xhr.responseJSON.data.id) {
				    console.log(xhr.responseJSON);
					xhr.responseJSON.data.id = xhr.responseJSON.data.id.toFixed(0);
				}
			}
			return event;
		});

        $rootScope.alertModel = $rootScope.alertMessage = $scope.alertModel = function(options){
            var params = {
                text:"我要提交咯！", //内容
                btnCancel:false, //取消按钮
                btnConfirm:true, //确认按钮
                closeSelf:false
            }
            $.extend(params,options);
            if(params.resCode=='00003'){
                $state.go("access.login");
                return false;
            }
            var reg1=/^[0][0-9]{3}[1-9]{1}$/.test(params.resCode);  //不是五个0 ，以0开头的
            var reg2=/^[1][0-9]{4}/.test(params.resCode);           //以1开头的
            var html='';
            html+='<div id="alertMessage" class="alertModel">'
            html+= '<div class="alertBox">'
            html+='<h4 class="text-title marTop-sm">温馨提示'
            html+='<i id="alertClose" class="iconfont icon-cancel cursor">&#xe62b;</i>'
            html+='</h4><div class="alertContent">'
            if(params.closeSelf){
                html+='<div class="alertText"><span>'+params.text+'<br>窗口将在<em id="Countdown">3</em>s后关闭</span></div><div class="text-center">'
            }else{
                // html+='<i  class="iconfont icon-cancel cursor"></i>'
                // html+='</h2><div class="alertContent">'
                if(reg2){
                    html+='<div class="alertText2 alertText"><i class="iconfont icon-normal">&#xe52e;</i><span class="text">'+params.text+'</span></div><div class="text-center">'
                }
                if(!params.resCode){
                    html+='<div class="alertText2 alertText"><i class="iconfont icon-stress">&#xe610;</i><span class="text">'+params.text+'</span></div><div class="text-center">'
                }
                if(reg1){
                    html+='<div class="alertText2 alertText"><i class="iconfont">&#xe501;</i><span class="text">'+params.text+'</span></div><div class="text-center">'
                }
                if(params.btnCancel&&!params.closeSelf){
                    html+='<button class="btn btn-radius btn-lg btn-danger" style="margin-right: 30px" id="cancleAlert">取消</button>'
                }
                if(params.btnConfirm&&!params.closeSelf){
                    html+='<button class="btn btn-radius btn-lg btn-primary" id="confirmAlert">确认</button>'
                }
            }
            '</div>'+
            '</div>'+
            '</div>';
            if(!$rootScope.onOff){
                $rootScope.onOff = !$rootScope.onOff;
                $('body').append(html);
            }
            var Countdown=$('#Countdown');
            var alertModel = $("#alertMessage");
            if(params.closeSelf){
                $('.alertText').find('span').css({
                    'lineHeight':'45px',
                    'letter-spacing':'5px'
                })
                $('.alertText').find('.iconfont').css({
                    'lineHeight':'92px'
                })
                return new Promise(function(resolve,reject){
                    var i=3;
                    var timer=setInterval(function(){
                        i--
                        Countdown.html(i);
                        if(i==0){
                            $rootScope.onOff=!$rootScope.onOff;
                            alertModel.remove();
                            resolve()
                            clearInterval(timer)
                        }
                    },1000);
                })
            }
            var alertFn=function(){
                return new Promise(function(resolve,reject){
                    $("#confirmAlert").click(function(){
                        alertModel.remove();
                        $rootScope.onOff = !$rootScope.onOff;
                        resolve(params.text);
                    })
                    $("#cancleAlert").click(function(){
                        $rootScope.onOff = !$rootScope.onOff;
                        alertModel.remove();
                        // reject();
                    });
                    $("#alertClose").click(function(){
                        $rootScope.onOff = !$rootScope.onOff;
                        alertModel.remove();
                    })
                })
            }
            return alertFn();
        }




    }]);